package com.exam.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.exam.demo.common.Result;
import com.exam.demo.controller.dto.QuestionDTO;
import com.exam.demo.entity.Answer;
import com.exam.demo.entity.ExamInfo;
import com.exam.demo.entity.Question;
import com.exam.demo.mapper.AnswerMapper;
import com.exam.demo.mapper.QuestionMapper;
import com.exam.demo.service.AnswerService;
import com.exam.demo.service.ExamInfoService;
import com.exam.demo.service.QuestionService;
import io.swagger.models.auth.In;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 功能描述
 *
 * @author yxj30
 * @date 2022/03/16  19:18
 */
@RestController
@RequestMapping("/answer")
public class AnswerController {
    @Resource
    AnswerService answerService;

    @Resource
    QuestionService questionService;

    @Resource
    ExamInfoService examInfoService;

    @Resource
    AnswerMapper answerMapper;


    //查找页面数据
    @GetMapping
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String answerName) {
        QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("answer_name", answerName);
        Page<Answer> page = answerService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }

    //更改和插入
    @PostMapping("/save")
    public Result insert(@RequestBody Answer answer) {
        return Result.success(answerService.saveOrUpdate(answer));
    }
    /*
     * 1. 先填充answer的确缺失数据
     * 2. 插入完整数据
     * 3. 统计考试结果
     * */
    //批量更改和插入答案
    @PostMapping("/saveList")
    public Result insertList(@RequestBody List<Answer> answerList) {
        System.out.println(answerList);
        String studentId = answerList.get(0).getStudentId();
        Integer paperId = answerList.get(0).getPaperId();
        Integer doTime = answerList.get(0).getDoTime();
        Date createTime = answerList.get(0).getCreateTime();
        //清空之前的数据，确保无脏数据
        answerService.remove(new QueryWrapper<Answer>().eq("student_id", studentId).eq("paper_id", paperId));
        examInfoService.remove(new QueryWrapper<ExamInfo>().eq("paper_id", paperId).eq("student_id", studentId));
        List<Integer> questionIdList = answerList.stream().map(Answer::getQuestionId).collect(Collectors.toList());
        List<Question> questionList = questionService.listByIds(questionIdList);
        //试卷状态
        Integer paperStatus = 2;
        //填充answer
        for (Answer answer :
                answerList) {
            //根据questionId查找原题
            List<Question> filterQuestionList = questionList.stream().filter(question -> {
                return question.getQuestionId().equals(answer.getQuestionId());
            }).collect(Collectors.toList());
            if (filterQuestionList.size() < 1) {
                return Result.error("500", "题目不存在");
            }
            /*填空题、客观题待批改*/
            if (filterQuestionList.get(0).getQuestionType() > 3) {
                paperStatus = 1;
                answer.setDoRight(-1);
                answer.setScore(0d);
                continue;
            }
            if (answer.getAnswer().equals(filterQuestionList.get(0).getCorrectAnswer())) {
                answer.setDoRight(1);
                answer.setScore(answer.getQuestionScore());
            } else {
                answer.setDoRight(0);
                answer.setScore(0d);
            }
        }
        System.out.println("处理后answerList:" + answerList);
        //统计
        answerService.saveOrUpdateBatch(answerList);
        ExamInfo examInfo = new ExamInfo();
        examInfo.setStudentId(studentId);
        examInfo.setPaperId(paperId);
        examInfo.setStatus(paperStatus);
        examInfo.setCourseId(questionList.get(0).getCourseId());
        examInfo.setDoTime(doTime);
        examInfo.setCreateTime(createTime);
        //计算系统判定得分
        QueryWrapper<Answer> answerQueryWrapper = new QueryWrapper<>();
        answerQueryWrapper.select("sum(score) as systemScore")
                .eq("student_id", studentId)
                .eq("paper_id", paperId);
        Map<String, Object> map = answerService.getMap(answerQueryWrapper);
        if (map == null) {
            examInfo.setSystemScore(0d);
        } else {
            examInfo.setSystemScore(Double.valueOf(map.get("systemScore").toString()));
            //如果不存在主观题
            if (paperStatus == 2) {
                //试卷总分与系统总分相等
                examInfo.setPaperScore(Double.valueOf(map.get("systemScore").toString()));
            }
        }
        //计算题目数量
        answerQueryWrapper = new QueryWrapper<>();
        answerQueryWrapper.select("count(*) as questionCount")
                .eq("student_id", studentId)
                .eq("paper_id", paperId);
        Map<String, Object> questionCountMap = answerService.getMap(answerQueryWrapper);
        if (questionCountMap == null) {
            examInfo.setQuestionCount(0);
        } else {
            examInfo.setQuestionCount(Integer.valueOf(questionCountMap.get("questionCount").toString()));
        }
        //计算答对的题目数量
        answerQueryWrapper = new QueryWrapper<>();
        answerQueryWrapper.select("count(*) as correctQuestionCount")
                .eq("student_id", studentId)
                .eq("paper_id", paperId)
                .eq("do_right", 1);
        Map<String, Object> correctQuestionCountMap = answerService.getMap(answerQueryWrapper);
        if (correctQuestionCountMap == null) {
            examInfo.setCorrectQuestionCount(0);
        } else {
            examInfo.setCorrectQuestionCount(Integer.valueOf(correctQuestionCountMap.get("correctQuestionCount").toString()));
        }
        examInfo.setStatus(paperStatus);
        answerQueryWrapper = new QueryWrapper<>();
        answerQueryWrapper.select("sum(question_score) as fullScore")
                .eq("student_id", studentId).eq("paper_id", paperId);
        Map<String, Object> fullScoreMap = answerService.getMap(answerQueryWrapper);
        if (fullScoreMap == null) {
            examInfo.setFullScore(0d);
        } else {
            examInfo.setFullScore(Double.valueOf(fullScoreMap.get("fullScore").toString()));
        }
        examInfoService.saveOrUpdate(examInfo);
        return Result.success(examInfo);
    }

    //批量更改和插入答案
    @PostMapping("/checkPaper")
    public Result checkPaper(@RequestBody List<QuestionDTO> answerList) {
        System.out.println(answerList);
        if (answerList.size() == 0) {
            return Result.error("10000", "answerList=null");
        }
        String studentId = answerList.get(0).getStudentId();
        Integer paperId = answerList.get(0).getPaperId();
        Integer doTime = answerList.get(0).getDoTime();
        Date createTime = answerList.get(0).getCreateTime();
        /*
        1.封装answer
        2.更改answer
        3.更新examInfo
         */
        for (int i = 0; i < answerList.size(); i++) {
            QuestionDTO questionDTO = answerList.get(i);
            Answer answer = new Answer();
            answer.setId(questionDTO.getId());
            answer.setDoRight(questionDTO.getDoRight());
            answer.setScore(questionDTO.getScore());
            int res = answerMapper.updateById(answer);
            if (res == 0) {
                return Result.error("10000", "更改分数错误");
            }
        }
        //更改examInfo
        UpdateWrapper<ExamInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("paper_id", paperId);
        updateWrapper.eq("student_id", studentId);
        updateWrapper.set("status", 2);//批改完成
        //计算系统总得分
        QueryWrapper<Answer> answerQueryWrapper = new QueryWrapper<>();
        answerQueryWrapper.select("sum(score) as score")
                .eq("student_id", studentId)
                .eq("paper_id", paperId);
        Map<String, Object> map = answerService.getMap(answerQueryWrapper);
        if (map == null) {
            updateWrapper.set("paper_score", 0d);
        } else {
            updateWrapper.set("paper_score", Double.valueOf(map.get("score").toString()));
        }
        //计算题目正确数量
        boolean update = examInfoService.update(null, updateWrapper);
        if(!update){
            return Result.error();
        }
        //获取新的examInfo
        ExamInfo examInfo = examInfoService.getOne(new QueryWrapper<ExamInfo>()
                .eq("student_id", studentId)
                .eq("paper_id", paperId));
        return Result.success(examInfo);
    }
    //删除
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(answerService.removeById(id));
    }
}
